package org.penguin.study.bk.basic

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicLong
import kotlin.concurrent.thread
import kotlin.system.measureTimeMillis

object CoroutineStudy {

    @JvmStatic
    fun main(args: Array<String>) {
        runBlocking {
            println("Terry -> 开始执行，协程马上暂停")
            delay(2000)
            println("Terry -> 协程马上结束")
        }

        testThreadAndCoroutine1()
    }

    private fun testThreadAndCoroutine1() {
        val elapsedThreadTime = measureTimeMillis { // measureNanoTime
            bigThreads()
        }

        val elapsedCoroutineTime = measureTimeMillis {
            bigCoroutines()
        }
        println("Terry -> 百万线程耗时: $elapsedThreadTime")    // 339940
        println("Terry -> 百万协程耗时: $elapsedCoroutineTime") //  26006
    }

    private fun bigThreads() {
        val c = AtomicLong()
        for (i in 1..1_000_000L)
            thread(start = true) {
                println("Terry -> thread $i")
                c.addAndGet(i)
            }
        println(c.get())
    }

    private fun bigCoroutines() {
        val c = AtomicLong()
        for (i in 1..1_000_000L)
            GlobalScope.launch {
                println("Terry -> coroutine $i")
                c.addAndGet(i)
            }
        println(c.get())
    }
}